
//
//  Canvers.m
//  拖拽手势画图
//
//  Created by MB__Lee on 2018/5/8.
//  Copyright © 2018年 MB__Lee. All rights reserved.
//

#import "Canvers.h"

@interface Canvers()
@property(nonatomic,assign)CGPoint beginPoint;//画图的起点

@property(nonatomic,strong)UIBezierPath *bezerPath;//贝塞尔曲线

@property(nonatomic,strong)NSMutableArray *pointArr;//绘制图形的所有点信息

@end


@implementation Canvers
-(UIBezierPath *)bezerPath{
    if (!_bezerPath) {
        UIBezierPath *path  = [UIBezierPath bezierPath];
        _bezerPath = path;
        path.lineWidth = 10; //设置线宽
        path.lineCapStyle = kCGLineCapSquare; //设置线的端点的样式（无端点、圆形端点、方形端点）
        path.lineJoinStyle = kCGLineJoinRound;//设置线的拐角处的样式（尖角，圆角，缺角）
        
        
    }
    
    return _bezerPath;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        NSLog(@"%s",__func__);
        [self addGesture];
    }
    return  self;
}
-(void)awakeFromNib{
    [super awakeFromNib];
    NSLog(@"%s",__func__);
    [self addGesture];//添加手势
}

-(void)addGesture{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:pan];
}
-(void)pan:(UIPanGestureRecognizer *)ges{
    
    
    
    CGPoint point = [ges locationInView:self];

    if (ges.state == UIGestureRecognizerStateBegan) {//拖拽手势开始
        if ([self.delegate respondsToSelector:@selector(canversViewBeginPrint:)]) {
            [self.delegate canversViewBeginPrint:self];
        }
        
        if (_removeAllPoints) {
            [self.bezerPath removeAllPoints];//移除绘制图形 的所有点
            
            [self.pointArr removeAllObjects];//将存放点的 数组 清空
        }
        
        
        _beginPoint = point;
        
        [self.bezerPath moveToPoint:point];
        
        
        
    }else if (ges.state == UIGestureRecognizerStateChanged){//拖拽手势状态改变
        [self.bezerPath addLineToPoint:point];
        [self setNeedsDisplay];//重汇
    }else if (ges.state  == UIGestureRecognizerStateEnded){
        [self.bezerPath closePath];
        [self setNeedsDisplay];//重汇
        
        //将点的存放点的数组 传递给 代理，让代理自行处理
        if ([self.delegate respondsToSelector:@selector(canversView:sendAllPoints:)]) {
            [self.delegate canversView:self sendAllPoints:self.pointArr];
        }
    }
    
    [self.pointArr addObject:@(point)]; //将点存放到数组里面
    
    if ([self.delegate respondsToSelector:@selector(canversView:streamSendPoints:)]) {
        [self.delegate canversView:self streamSendPoints:self.pointArr];
    }
    
}



- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    [[UIColor greenColor] setStroke];//线的颜色
    [self.bezerPath stroke];
}

#pragma mark ---懒加载
-(NSMutableArray *)pointArr{
    if (!_pointArr) {
        _pointArr = [NSMutableArray array];
    }
    return  _pointArr;
}


@end
